﻿namespace Probel.Client.Commands
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    using Probel.Client.StatReaderReference;

    [Command("list", "ls", "List all the entries stored in the database")]
    public class ListCommand : ICommand
    {
        #region Methods

        public void Execute(dynamic context)
        {
            var proxy = context.ProxyReader as IStatReader;
            var args = context.Arguments as string[];

            var result = proxy.GetLogEntries();

            Display(result.Entries);
        }

        private static void DisplayHeader()
        {
            Console.WriteLine("Legend");
            Console.WriteLine("------");
            Console.ForegroundColor = ConsoleColor.Black;
            Console.BackgroundColor = ConsoleColor.Green;
            Console.WriteLine("This version was used in the last five days.");
            Console.ResetColor();

            Console.ForegroundColor = ConsoleColor.DarkRed;
            Console.BackgroundColor = ConsoleColor.Yellow;
            Console.WriteLine("There was zero days before inscription and last usage. Last usage is older than 5 days.");
            Console.ResetColor();

            Console.WriteLine();
            Console.WriteLine();

            Console.BackgroundColor = ConsoleColor.DarkBlue;
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("{0,-4} - {1,-14} - {2,-5} - {3,-10} - {4,10}", "Nr", "Version", "Cnt", "Inscr.", "Last con.");
            Console.ResetColor();
        }

        private void Display(LogEntry[] entries)
        {
            var i = 1;
            DisplayHeader();
            foreach (var item in entries)
            {
                var elapsed = (int)(item.LastConnection - item.RegistrationDate).TotalDays;
                if ((DateTime.Now - item.LastConnection).TotalDays < 5)
                {
                    Console.ForegroundColor = ConsoleColor.Black;
                    Console.BackgroundColor = ConsoleColor.Green;
                }
                else if (elapsed == 0)
                {
                    Console.ForegroundColor = ConsoleColor.DarkRed;
                    Console.BackgroundColor = ConsoleColor.Yellow;
                }
                Console.WriteLine("{0,4} - {1,-14} - [{2,3:0}] - {3:d} - {4:d}"
                    , i++
                    , item.WindowsName
                    , elapsed
                    , item.RegistrationDate
                    , item.LastConnection);
                Console.ResetColor();
            }
        }

        #endregion Methods
    }
}